import express from 'express';
import * as categories from '../../controllers/categories.js';
import * as articles from '../../controllers/articles.js';
// 引入JWT验证中间件
import { auth } from '../../auth/auth.js';
const router = express.Router();

// 5. 所有文章类别
router.get('/list', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/category/list 请求...');
    let data = await categories.selectAllCategories();
    res.send({
      code: 200,
      msg: "获取成功",
      data: data.map(item => ({
        id: item.id,
        name: item.name,
        slug: item.slug
      }))
    });
  } catch (error) {
    console.error('获取文章类别失败:', error);
    res.status(500).send({
      code: 500,
      msg: "获取文章类别失败"
    });
  }
});

// 6. 新增文章类别
router.post('/add', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/category/add 请求...');
    
    // 健壮性参数校验
    let name = req.body?.name ?? "";
    let slug = req.body?.slug ?? "";
    if (name == "" || slug == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    // 检查name是否重复
    let nameExists = await categories.checkCategoryNameExists(name);
    if (nameExists.length > 0) {
      return res.send({
        code: 200,
        msg: "name重复"
      });
    }
    
    // 检查slug是否重复
    let slugExists = await categories.checkCategorySlugExists(slug);
    if (slugExists.length > 0) {
      return res.send({
        code: 200,
        msg: "slug重复"
      });
    }
    
    // 通过所有检查，可以新增
    await categories.insertCategory(name, slug);
    res.send({
      code: 200,
      msg: "增加成功"
    });
  } catch (error) {
    console.error('新增文章类别失败:', error);
    res.status(500).send({
      code: 500,
      msg: "增加失败"
    });
  }
});

// 7. 根据id查询指定文章类别
router.get('/search', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/category/search 请求...');
    
    // 健壮性参数校验
    let id = req.query?.id ?? "";
    if (id == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    let data = await categories.selectCategoryById(id);
    if (data.length === 0) {
      return res.status(404).send({
        code: 404,
        msg: "类别不存在"
      });
    }
    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        id: data[0].id,
        name: data[0].name,
        slug: data[0].slug
      }
    });
  } catch (error) {
    console.error('查询文章类别失败:', error);
    res.status(500).send({
      code: 500,
      msg: "查询失败"
    });
  }
});

// 8. 编辑文章类别
router.post('/edit', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/category/edit 请求...');
    
    // 健壮性参数校验
    let id = req.body?.id ?? "";
    let name = req.body?.name ?? "";
    let slug = req.body?.slug ?? "";
    if (id == "" || name == "" || slug == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    // 检查类别是否存在
    let categoryData = await categories.selectCategoryById(id);
    if (categoryData.length === 0) {
      return res.status(404).send({
        code: 404,
        msg: "类别不存在"
      });
    }
    
    // 获取当前类别信息
    let currentCategory = categoryData[0];
    
    // 健壮性判断：检查是否没有任何修改
    if (currentCategory.name === name && currentCategory.slug === slug) {
      return res.send({
        code: 200,
        msg: "数据未发生变更，无需修改"
      });
    }
    
    // 检查name是否与其他类别重复（排除自己）
    let nameExists = await categories.checkCategoryNameExistsExcludeId(name, id);
    if (nameExists && nameExists.length > 0) {
      return res.send({
        code: 200,
        msg: "name重复"
      });
    }
    
    // 检查slug是否与其他类别重复（排除自己）
    let slugExists = await categories.checkCategorySlugExistsExcludeId(slug, id);
    if (slugExists && slugExists.length > 0) {
      return res.send({
        code: 200,
        msg: "slug重复"
      });
    }
    
    // 通过所有检查，可以更新
    await categories.updateCategory(id, name, slug);
    res.send({
      code: 200,
      msg: "编辑成功"
    });
  } catch (error) {
    console.error('编辑文章类别失败:', error);
    res.status(500).send({
      code: 500,
      msg: "编辑失败"
    });
  }
});

// 9. 删除文章类别
router.post('/delete', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/category/delete 请求...');
    
    // 健壮性参数校验
    let id = req.body?.id ?? "";
    if (id == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    // 方式1: 检查是否为默认类别（如果有state字段）
    let categoryData = await categories.selectCategoryById(id);
    if (categoryData.length === 0) {
      return res.status(404).send({
        code: 404,
        msg: "类别不存在"
      });
    }
    
    let category = categoryData[0];
    // 如果state=1表示默认类别，不能删除
    if (category.state && category.state == 1) {
      return res.send({
        code: 200,   // 请求没问题，正常处理了，只是业务规则不允许删除
        msg: "默认分类不能删除"
      });
    }
    
    // 方式2: 检查是否有关联文章
    let relatedArticles = await articles.selectArticlesByCategory(id, 1, 1); 
    if (relatedArticles.length > 0) {
      return res.send({   // 请求被成功接收、处理，没有技术错误，是预期的业务逻辑判断
        code: 200,
        msg: "分类关联文章，不能删除"
      });
    }
    
    // 通过所有检查，可以删除
    await categories.deleteCategory(id);
    res.send({
      code: 200,
      msg: "删除成功"
    });
  } catch (error) {
    console.error('删除文章类别失败:', error);
    res.status(500).send({
      code: 500,
      msg: "删除失败"
    });
  }
});

export default router;
